<template>
	<div class="login-scan">
		<div class="qr-code" v-loading="loading">
			<img :src="qrUrl" alt="" />
			<div class="cover" v-if="qrCountTime === 0">
				<i class="el-icon-refresh-left" @click="getQrCode()"
					>二维码已失效<br />新刷新重新获取</i
				>
			</div>
		</div>
		<p>已绑定微信的账号，可直接扫码登录</p>
	</div>
</template>

<script>
import { mapMutations } from 'vuex';
import QRCode from 'qrcode';
export default {
	name: 'scan',
	components: {},
	data() {
		return {
			loading: true,
			qrUrl: null,
			checkTimer: null,
			qrCountTime: null
		};
	},
	async created() {
		this.getQrCode();
	},
	methods: {
		...mapMutations(['SET_TOKEN']),
		// 获取二维码
		getQrCode() {
			clearInterval(this.checkTimer);
			clearInterval(this.qrCountDown);

			this.loading = true;

			this.$service.common
				.qrcode({
					type: 0,
					source: 0
				})
				.then(async res => {
					this.qrUrl = await QRCode.toDataURL(res.url, {
						errorCorrectionLevel: 'H',
						type: 'image/jpeg',
						margin: 1
					});
					this.loading = false;

					// 启动倒计时
					this.qrCountTime = 120;
					this.qrCountDown = setInterval(() => {
						this.qrCountTime--;
						if (this.qrCountTime === 0) {
							// 结束倒计时和接口校验
							clearInterval(this.checkTimer);
							clearInterval(this.qrCountDown);
						}
					}, 1000);

					// 监听二维码扫描
					this.checkTimer = setInterval(() => {
						this.$service.common
							.wechatLogin({
								ticket: res.ticket
							})
							.then(res => {
								if (res) {
									if (res.status === 1) {
										this.SET_TOKEN({ token: res.token });
										this.$parent.next();
									} else {
										this.$message.error(res.msg);
									}
									clearInterval(this.checkTimer);
									clearInterval(this.qrCountDown);
								}
							});
					}, 2000);
				});
		}
	},
	destroyed() {
		clearInterval(this.checkTimer);
	}
};
</script>

<style lang="stylus" scoped>
.login-scan {

	.qr-code {
		width 214px
		height 214px
		margin 0 auto 20px
		position relative
		img {
			width 100%
			border 10px solid $color-white
		}
		.cover {
			background rgba(0,0,0,0.85);
			position absolute
			width 214px
			height 214px
			top 0
			left 0
			display flex
			justify-content center
			align-items center
			i {
				color $color-white
				font-size 14px
				cursor pointer
				display flex
				justify-content center
				align-items center
				flex-direction column
				text-align center
				line-height 20px
				&:before {
					font-size 20px
					margin-right 4px
				}
			}
		}
	}
	p {
		text-align center
		color $color-black
		font-size 16px
	}
}
</style>
